====== Random generator ======

The random generator is a functional component for the questionnaire. It draws one element from a predefined list of elements (ballots) and saves its value in a variable. The picket value can be retrieved via ''[[:en:create:functions:value]]''  and used in a [[:en:create:filters|Filter]], to randomly vary contents of the questionnaire. This would e.g. allow the random assignment of participants to experimental groups.

The random generator developed from the [[:en:create:random_urns|urn-function]] and ensures (like the urn) that all ballots are drawn equally (option //mode of drawing//). This is especially important when experimental groups have to be of equal size. Because an unrestricted random sampling could lead to massive deviations in group sizes (especially in case of smaller samples).

The extensive examples in the chapter [[:en:create:randomization]], concerning the use of filters for experimental stimuli, are also transferable to the random generator. This can be done by placing the random generator element on the questionaire page (instead of the operator ''[[:en:create:functions:urndraw]]''). The drawn Number can be subsequently retrieved via ''[[:en:create:functions:value]]'' (as described in the urn thread).

**Hint:** If the random variation doesn’t work as desired, the debug-informations in the questionnaire will provide fast explanations. (Read more at [[:en:create:filter-solving]].)


===== Differences between random generator and urn function =====

  * For the second drawn ballot two kinds of values are available: first the numeric code and second the inscribed text for the ballot (e.g. the file name of a image, as seen in the example below)

  * The random generator can draw multiple ballots during one interview (option //Amount of ballots per interview//) ensuring that no ballot can be drawn twice

  * The random generator yields only one value (including it’s inscription) per ballot. Combinations are only possible using the following workaround: The combination is saved as an inscription and separated after the drawing using [[http://php.net/manual/de/function.explode.php|explode()]].

===== Example: Varying screen-stimulus =====

This example describes the use of the random generator in an experiment with 3 experimental groups (with one image stimulus each) and a control group (no stimulus).


===== Preperations =====

  * Upload the 3 image stimuli to **Image and Media Files** and note the filenames. Take also care for case sensitivity (so Datei.jpg doesn’t equal datei.JPG).
  * Create a new question of the „random generator“ type (in the following case the question is named ZG01). Enter the following ballots (Note that file names can deviate from case to case.) into the question:

<code>
1 = stimulusA.jpg
2 = stimulusB.jpg
3 = stimulusC.jpg
4 = control_group
</code>

===== Application =====

Under **Create a Questionnaire** you can drag and drop the random generator to the page you want the picture to appear. Now place (s. also [[:en:create:php]]) the following PHP code beneath (!) the random generator:

<code php>
// Retrieve the numeric codes  (1 bis 4)
$code = value('ZG01');
// The control group has to be treated differently
if ($code == 4) {
  // Kontrollgruppe - nichts anzeigen
} else {
  // The inscription is saved as a value label – in this example the image name
  $img = value('ZG01', 'label');
  // The HTML-Tag <img> shows an image, the filename will be shown with src
  html('
    <div style="margin: 3em; text-align: center">
      <img src="'.$img.'" alt="" />
    </div>
  ');
}
</code>


==== Addition 1 ====

Not every experimental variation is resolved by displaying a single image. The following PHP code shows how to display another image on another position. The variation happens contingent by the first image, so if someone got the image 1a displayed he will on this position get image 1b.
This time the filename for the image will not be saved directly into the random generator (like above) but in an array ([[:en:create:array]]), which will assign a filename to every experimental group using ''%%=>%%''.

<code php>
// Retrieving of the numeric codes (1 to 4)
$code = value('ZG01');
// The control group must (here to) be treated differently
if ($code == 4) {
  // Control group – display nothing
} else {
  // Array, that saves an image for every group
  $bilder = array(
    1 => 'stimulusA2.jpg',
    2 => 'stimulusB2.jpg',
    3 => 'stimulusC2.jpg'
  );
  // With the square brackets an element from the array is read
  $bild = $bilder[$code];
  // Display oft he image as above
  html('
    <div style="margin: 3em; text-align: center">
      <img src="'.$bild.'" alt="" />
    </div>
  ');
}
</code>

**Note:** This PHP-code only works, if at an earlier time in the same interview another page with a random generator question was used. If you start the interview for testing directly on the page with the PHP-code (but without a random generator, which occurs earlier in the interview), you will receive an error message.

==== Addition 2 ====

Instead of an image also a question or a text module can be integrated. The following PHP code displays an individual text module (create under **Text Elements and Labels** -- and in groups 1 and 2 the question ''AB01'', in the other groups the question ''BB01'').

<code php>
// Retrieving of the numeric codes (1 to 4)
$code = value('ZG01');
// Varriing the text modules
if ($code == 1) {
  text('text EG1');
} elseif ($code == 2) {
  text('text EG2');
} elseif ($code == 3) {
  text('text EG3');
} elseif ($code == 4) {
  text('text KG');
}
// Variing the questions
if (($code == 1) or ($code == 2)) {
  question('AB01');
} else {
  question('BB01');
}
</code>

**Note:** view in addition to ''[[:en:create:functions:text]]'' and ''[[:de:create:functions:question]]'' also the orders ''[[:en:create:functions:replace]]'' and ''[[:en:create:functions:setpageorder]]''.


===== Example: Show multiple images =====
In this example participants should rate 300 images. To achieve this each participant has to rate 20 different pictures - each on a different page.
==== Preperation ====
  * Upload all images to **Images and Media Data**
  * Create a new question of the „random generator“ type (in the following case the question is named ZG03).
    * Enter the file names of the images as ballots into the question, one filename per line. You don’t have to put numbers ahead, they will be provided automatically after saving.
    * For the option //Number of ballots per interview//, enter the number of images that you want to show (in this case 20).
  * For the ratings create 20 questions with ID’s ranging from ''AB01'' to ''AB20'' – the function “Duplicate Question” (You will find it above the question when you edit it.) will help you to save time. If it’s only one rating per image you could also create one question with 20 images.

==== Application ====
Create one (!) page to display the images and the corresponding questions using **Create a Questionnaire**. Place the random generator on this page and beneath it the following PHP code (s. also [[:en:create:php]]). The command ''[[:en:create:functions:looppage]]'' provides that the same page will be shown multiple with different content. The command ''[[http://php.net/manual/de/function.sprintf.php|sprintf()]]'' formats a number – in PHP code a double-digit number will be created with a leading 0 (e.g. 3 will be „03“).

<code php>
// loopPage(20) provides a number between 0 and 19 (plus one at every repetition)
$i = loopPage(20);  // Here you can enter the number of images you want to show
// Show the chosen picture
$varID = 'ZG03x'.sprintf('%02d', $i + 1);  // Variable IDs are ZG03x01 to ZG03x20
$img = value($varID, 'label');
// The HTML-Tag <img> shows one image, the filename will be shown with src 
html('
  <div style="margin: 3em; text-align: center">
    <img src="'.$img.'" alt="" />
  </div>
');
// Create the fitting question ID and show the question using question()
question(id('AB', $i + 1)); // Question IDs AB01 to AB20
</code>

If you didn’t create 20 questions (''AB01'' to ''AB20''), but only one question AB01 with 20 items, substitute the last 3 lines as follows. The +1 behind the variable ''$i'' is needet, because ''loopPage()'' starts counting at 0 instead of 1.

<code php>
// Shows the item fitting to the question using question() 
question('AB01', $i+1);
</code>


===== Example: Rate multiple political parties =====

In the following example the participants have to evaluate political parties using many different criteria. Altogether 6 parties have to be evaluated – but every participant should only have to evaluate two of them chosen randomly.

==== Option 1 ====

This Option will always save the answers to the first drawn party in the same variable. If you use e.g. 20 variables per party, your dataset will have 40 variables for party evaluations. This is overseeable, but a little bit more difficult to analyse, because one half of the answers for e.g. the green party will be saved in set of variables ''P1xx'' while the other half will be saved in set of variables ''P2xx''. Use this option if you have (a) many items to evaluate and (b) are really good in analysing the data.

  * Create a category (e.g. “P1”) in your questionnaire, with all questions you want to ask about a party. Instead of the party name enter the [[:en:create:placeholders|placeholder]] ''%partei%''.
  * Create a copy of the category, by downloading the category as an XML-file (Arrow down symbol in the toolbar above the question) and importing the file under //New category//. In this example the label ''P2'' is used.
  * Create a questionnaire under ** Create a Questionnaire ** and place the questions from ''P1'' and ''P2'' on their intendet positions. In this questions it is assumed that at first all questions from ''P1'' and subsequently all questions from ''P2'' will be asked. In order to mix the questions different placeholders (e.g. ''%partei1%'' und ''%partei2%'') would have to be used in the questions and items.
  * Create a question of the type "Random generator" (in this example it is assumed to have the label ZG04). In the question, enter the following //ballots (contents)//  and at //Number of ballots per interview// enter the value 2.

<code>
1 = CDU/CSU
2 = SPD
3 = Die Grünen
4 = Die Linke
5 = Piraten
6 = AfD
</code>

Place the random generator under ** Create a Questionnaire ** on the first page with a ''P1''-question (or bevore). Beneath it, place the following PHP code.:

<code php>
$name = value('ZG04x01', 'label');  // Name of the party (CDU/CSU to AfD)
replace('%partei%', $name);
</code>


From there on the placeholder ''%partei%''  will be replaced in every question by the drawn Names. The numeric code of the party can be read using ''$code = value('ZG04x01');'' to e.g. use a text module or a party logo (s. above) 

Place the following PHP-code on the first page with a „P2“-question:

<code php>
$name = value('ZG04x02', 'label');
replace('%partei%', $name);
</code>

If you want to mix the questions about the two parties, and if you have therefore used the placeholders ''%partei1%'' and ''%partei2%'', place the following PHP-code beneath the random generator:

<code php>
$name1 = value('ZG04x01', 'label');
replace('%partei1%', $name1);
$name2 = value('ZG04x02', 'label');
replace('%partei2%', $name1);
</code>


==== Option 2 ====

It’s also possible to create own questions for every party. If you ask for 20 variables per party, the dataset will sum up to 120 variables – but therefore the evaluations of a party will always be saved into the same variables. The creation of that many questions might be more effortful but it’s also way easier to analyse.

    * Create a category (e.g. “P1”) in your questionnaire, with all questions you want to ask about the first party.
    * In this option you can enter the party name directly into the question (and change it in every copy manually) or
    * Instead of entering the party name you can enter the [[:en:create:placeholders|placeholder]] ''%partei%'' and set it up using ''[[:en:create:functions:replace]]'', thus saving a lot of effort.
   * Create 5 copies of the category by downloading the category as an XML-file (Arrow down symbol in the toolbar above the question) and subsequently import it multiple times using //New Category//. In this example the copys will be labelled ''P2'' to ''P6''.
  * Create a question of the type "Random generator" (in this example it is assumed to have the label ZG04). In the question, enter the following //ballots (contents)//  and at //Number of ballots per interview// enter the value 2.

<code>
1 = CDU/CSU
2 = SPD
3 = Die Grünen
4 = Die Linke
5 = Piraten
6 = AfD
</code>

Place the random generator under ** Create a Questionnaire ** on or before the first party question.

If you are working with the placeholder ''%partei%'', you have to enter the following PHP-code at the begin of the two blocks:

<code php>
$name = value('ZG04x01', 'label');  // At the second block then with ZG04x02
replace('%partei%', $name);
</code>

The questions have the labels ''P101'' for the first question about the first party (CDU/CSU), ''P201'' for the first question about the second party (SPD) etc. Now there are two possible ways to display the desired question. You could use an IF-filter (s. also [[:en:create:filters]]) or the label "assemble". The assembly is way more compact. If the question labels are not perfectly parallel (e.g. because an additional question should be shown for one of the parties) only one filter will work here.

Place the following PHP-code where the corresponding question should be asked. So if you have 9 questions per party, place the code 9 times in the first partys block and 9 times in the second partys block. In the second block ''ZU04x01'' has to be replaced with ''ZU04x02''. The question labels have to be adapted in every PHP-code.

=== PHP-code with assembly ===

<code php>
$code = value('ZG04x01');
$kennung = 'P'.$code.'01';  // The point (.) connects strings (Texte)
question($kennung);
</code>

=== PHP-code with filters ===

<code php>
$code = value('ZG04x01');
if ($code == 1) {
  question('P101');
} elseif ($code == 2) {
  question('P201');
} elseif ($code == 3) {
  question('P301');
} elseif ($code == 4) {
  question('P401');
} elseif ($code == 5) {
  question('P501');
} elseif ($code == 6) {
  question('P601');
}
</code>


==== Option 3 ====

Another option would be to place all questions to all parties in the questionnaire and to give labels to the pages (s. bellow e.g. "P1Begin", "P1End", "P2Begin", "P2End" etc.) and to subsequently work with ''[[:en:create:functions:setpageorder]]'', in order to show the fitting page blocks.

This variant is more vulnerable to errors (e.g. that somebody forgets to answer a question) and makes the questionnaire confusing. The command ''[[:de:create:functions:setpageorder]]'' is quite useful to vary the order of question-blocks -- but there are more elegant solutions for the selection of stimuli or to skip pages.

Due to the limited use, we only present some example PHP code on this option. If you still decide for this option, place the following PHP-code on the last page of the generic part (the part everybody has to answer the same way before the branching occurs). He will display the two party blocks separated by an intermediate part between them ("middleBegin" to "middleEnd") and continue to the page with the label "demografie". Again you have to place the PHP-code after placing the random generator as described above.

<code php>
$pages = array();
// Numeric code of the first party
$code1 = value('ZG01x01');
// Write the fitting pages into the array
if ($code1 == 1) {
  $pages[] = 'P1Begin-P1End';
} elseif ($code1 == 2) {
  $pages[] = 'P2Begin-P2End';
} elseif ($code1 == 3) {
  $pages[] = 'P3Begin-P3End';
} elseif ($code1 == 4) {
  $pages[] = 'P4Begin-P4End';
} elseif ($code1 == 5) {
  $pages[] = 'P5Begin-P5End';
} elseif ($code1 == 6) {
  $pages[] = 'P6Begin-P6End';
}
// Complement the pages fort he intermediarry part
$pages[] = 'middleBegin-middleEnd';
// Numeric code of the second party
$code2 = value('ZG01x02');
// Write the pages for the second party into the array
if ($code2 == 1) {
  $pages[] = 'P1Begin-P1End';
} elseif ($code2 == 2) {
  $pages[] = 'P2Begin-P2End';
} elseif ($code2 == 3) {
  $pages[] = 'P3Begin-P3End';
} elseif ($code2 == 4) {
  $pages[] = 'P4Begin-P4End';
} elseif ($code2 == 5) {
  $pages[] = 'P5Begin-P5End';
} elseif ($code2 == 6) {
  $pages[] = 'P6Begin-P6End';
}
// Determine where it shall continue
$pages[] = 'demografie';
// Set the page order
setPageOrder($pages);
</code>

Also this PHP-code can be written more compact if the labels for the pages are "assembled":

<code php>
$code1 = value('ZG01x01');
$code2 = value('ZG01x02');
setPageOrder(
  'P'.$code1.'Begin-P'.$code1-'End',
  'middleBegin-middleEnd',
  'P'.$code2.'Begin-P'.$code2-'End',
  'demografie'
);
</code>

===== Example: Varying page sequence =====
The questionaire of this example belongs to the “Within-Subject” experimental design. This means the questionnaire has a generic part, followed by some pages containing the first stimulus, followed by some puffer pages and some pages with the second stimulus. The sequence of the two units of stimuli should vary randomly.
==== Preperation ====
  * Create a new question of the „random generator“ type (in the following case the question is named ZG02). Enter the following ballots (Note that file names can deviate from case to case.) into the question:
<code>
1 = experimentalgroup 1
2 = experimentalgroup 2
</code>
  * Give ID’s to the pages of the questionnaire using ** Create a questionnaire** ([[:en:glossary#page_ids|Page IDs]]). You can basically choose your ID’s freely, for this example the following ID’s where used:
  * The first Page which belongs to stimulus A receives the ID “beginA”.
  * The last Page which belongs to stimulus A receives the ID “endA”.
  * The first Page which belongs to the puffer pages receives the ID “beginMiddle”.
  * The last Page which belongs to the puffer pages receives the ID “endMiddle”.
  * The first Page which belongs to stimulus B receives the ID “beginB”.
  * The last Page which belongs to stimulus B receives the ID “endB”.
  * The first Page of the final part (which follows directly to “endB”) receives the ID “final”.

==== Application ====
Under **Create a Questionnaire** drag and drop the random generator to the last page of the generic part. The following page should respectively have the ID „beginA“.

Place the following PHP-code beneath the random generator (s. auch [[:en:create:php]]). The order ''[[:en:create:functions:setpageorder]]'' provides that the pages appear in the desired sequence.

<code php>
$code = value('ZG02');
if ($code == 1) {
  // Keeps the normal sequence – it is possible to omit this order...
  setPageOrder('beginA-endA', 'beginMiddle-endMiddle', 'beginB-endB', 'final');
} else {
  // Reverse sequence of the units A and B
  setPageOrder('beginB-endB', 'beginMiddle-endMiddle', 'beginA-endA', 'final');
}
</code>

